import cCarcontent from "components/carcontent";
import cCarcontent4 from "components/carcontent4";
import goodScreen from "components/ui_components/yz_goodScreen";
import cSort from "components/sort";
import { Toast,Skeleton,Image as VanImage   } from "vant";
import BScroll from "better-scroll";
import { mapState } from "vuex";

var specsManage = []; //选择池 用于排序
var optionsId = ""; //选择后的 规格ID
var optionsMaxCount = 1;
var OldGoodsNum = null;

let categoryApi = {
  home: "goods.category.category-home",
  children: "goods.category.get-children-category",
  goods: "goods.category.get-goods-list-by-category-id"
};
export default {
  data() {

    return {
      loading:true,
      parentTitle:"",
      select_top:0,
      swiperOption: {
        autoHeight: true,
        autoplay: false,
        loop: false,
        initialSlide: 0,
        pagination: {
          el: ".swiper-pagination"
        }
      },
      webdesImage:[],
      decorate_config:{
        classify_position:"",//二级分类显示位置：1=右侧；2=和一级分类显示左侧
        classify_style:"",//分类样式：1=左侧分类名称+右侧商品列表；2=左侧分类名称+右侧二级分类列表
        goods_sort:"",//商品排列方式：0=不显示；1=竖排两列；2=横排
        inner_click:"",//点击跳转：1=商品详情；2=搜索页；3=旧三级分类页
        cart_style:"",//购物车：0=不显示；1=加入购物车
      },
      parentId:"",

      child_category_active:1,
      switch_flag:false,
      one_id:"",
      lastIndex:"",
      commodity:false,
      first_category_name:"",
      showGoodScreen: false,
      searchScreen: {},
      integral: window.localStorage.getItem("integral") || "积分",
      debounce_timer: null,
      brandShow: "",
      categoryShow: "",
      active: 9999,
      active2: true,
      allLoaded: false,
      topStatus: "",
      err: "",
      turl: "/category",
      arg: { index: 10, item: "pinch" },
      parentTitle: this.$i18n.t("推荐分类"),
      onelist: [],
      contentlist: {},
      contentlist_one: {},
      category_template: "01", //后台开启那个模板
      cartInfo: {},

      list: [],
      goodsInfo: {},
      advimg: window.localStorage.adv_img,
      carts: [],
      cartIDs: [],
      specid: "", //规格ID
      goodsCarts: [], //购物车转为goods key的数组
      goodsCartsTotal: [],
      activeName: [], //分类折叠面板
      secondaryId: "", //二级分类id
      threeId: "", //三级分类ID
      threeInfo: [], //三级商品列表
      show2: false, //规格弹窗
      showTitle: "", //分类折叠标题
      titleInfo: {}, //用于保存分类折叠时自定义标题分类
      foodInfo: [],
      popTitle: "",
      popPrice: "",
      popNum: 0,
      popStock: "",

      //more
      page: 1, //分页数，当前页数
      isLoadMore: false, //判断是否要加载更多的标志
      total_page: 0, //总页数
      activatId: "", //当前的分类id
      LoadMoreTest: "",
      scrollMargin: 0,

      isGetCart: true, //是否请求获取购物车接口数据
      ADImg: "", //广告图片地址
      ADUrl: "", //广告跳转链接
      isRecommend: true, //是否为推荐分类

      isCategoryMore: false, //装修01，03导航栏分类加载更多
      isCategory_total_page: 0,
      isCategoryPage: 1,

      main_category_page: 1,
      main_category_total: 0,

      isSelfPickCategory: false, //是否为供应商管理的自提点的分类页，#75504；如是，则只显示自提点关联的供应商的商品和平台商品（包含聚合供应链商品），其他供应商商品不显示，没有关联自提点的供应商商品也不显示。
      deliverId: 0, //自提点id

      isMultiSpecs: false, //多规格商品是否显示会员价
      specsVIPPrc: null, //规格商品会员价

      tab_list:[],
      tiktok_list:[],//抖音cps商品
      current_goods_key:"shop",
      tiktok_details:{
        search_type:0,
        order_type:0,
        cate_id:''
      },
      sort: {
        up: 0,
        down: 0
      },
      currrent_category_index: 0,
      choose_index: 1,
    };
  },
  computed: {
    ...mapState(["category", "blurst"]),
    zoneId() {
      if (this.$store.state.zoneId == "") {
        this.$store.commit("setZoneId", window.localStorage.getItem("zoneId"));
      }
      return this.$store.state.zoneId;
    },
    vip_price_txt(){
      if (this.$store.state.shopLanguage.goods) {
        // 会员价  系统自定义
        return this.$store.state.shopLanguage.goods.vip_price || "会员价";
      } else {
        return "会员价";
      }
    },
    checkPluginSort(){
      if(this.$route.name == 'coffee_machine_cate'){
        return false
      }else{
        return true
      }
    },
    checkPlugin(){
      if(this.$route.name == 'coffee_machine_cate'){
        return false
      }else if(this.active2||(this.list.set&&this.list.set.cat_level==3&&this.decorate_config.classify_position==2)||this.decorate_config.classify_position==1){
        return true;
      }else{
        return false
      }
    },
    // 分类|卷后价显示
    coupon_price_displayc(item){
      return function(item){
        let str = "";
        if(!item) return ''
        if(item.hasOwnProperty('first_cat_name')){
          str = `${item.first_cat_name}`
          if(item.points_price_display && Number(item.points_price_display.goods_price)){
            str += '|'
          }
        }
        if(item.points_price_display && Number(item.points_price_display.goods_price)){
          str += `兑后价${this.$i18n.t("money")}${item.points_price_display.goods_price}`
        }
        return str;
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === "goods" || from.name === "grab_group" || from.name === "newRetailSalesGood") {
      if (toGoodListIOS) {
        toGoodListIOS({ body: "toGoodListIOS" });
      }
    }
    next();
  },
  methods: {
    init_head_height(){
      if(this.$refs['category-head']){
        this.select_top =this.$refs['category-head'].offsetHeight + 'px';
      }
    },
    // 分类|卷后价显示
    coupon_price_displayc_style(){
      let colorObj = [
        {color:'#F96D20',backgroundColor:'#FFEDE4'},
        {color:'#207EF9',backgroundColor:'#E4EFFF'},
        {color:'#F15353',backgroundColor:'#FEEAEA'},
        {color:'#A320F9',backgroundColor:'#F4E4FF'},
        {color:'#00922C',backgroundColor:'#E0F2E5'},
      ]
      let ran = Math.floor(Math.random() * (4 - 0 + 1)) + 0;
      return colorObj[ran];
    },
    point_goods(good){
     return good.has_option == 1 ? !good.point_goods.max_point || good.point_goods.min_point == good.point_goods.max_point? good.point_goods.min_point
      : good.point_goods.min_point + "-" + good.point_goods.max_point
    : good.point_goods.min_point
    },
    link_tiktok_cps(data){
      this.$router.push(this.fun.getUrl('TikTokDetail',{id:data.product_id}))
    },
    onChangeGoods(data){
      this.current_goods_key = data.key;
      if(data.key == 'tiktok'){
        this.TikTokScroll = null;
        this.err = false;
        this.active = 0;
        $http.get("plugin.tiktok-cps.api.goods.good-cate",{page:1},'loading').then(res=>{
          if(res.result==0){
            return this.$toast(res.msg);
          }
          this.onelist = res.data.data || [];
          this.tiktok_details.cate_id = res.data.data[0].cate_id;
          this.main_category_total = res.data.last_page;
          this.isLoadMore = true;
          this.getTikTokGoods()
        })
      }else{
        this.active2 = true;
        this.active = 9999;
        this.foodScroll = null;
        // this.getCategoryNew();
        this.get_classify('tab');
      }
    },
    getTikTokGoods(){
      this.foodScroll = null;
      let json = {
        ...this.tiktok_details,
        page:this.page,
        search_type:this.tiktok_details.search_type,
        order_type:this.tiktok_details.order_type
      }
      $http.get('plugin.tiktok-cps.api.goods.good-list',json,"").then(res=>{
        if(res.result == 0){
          return this.$toast(res.msg);
        }
        let {current_page,products,last_page} = res.data;
        this.tiktok_list=products;
        this.page = Number(current_page);
        this.total_page = Number(last_page);

        this.$nextTick(()=>{
          if(!this.TikTokScroll){
            this.TikTokScroll = new BScroll(this.$refs.TikTokWrapper, {
              click: true,
              scrollY: true,
              probeType: 3,
              swipeBounceTime: 500,
              useTransition: false,
              mouseWheel: true
            });
            this.TikTokScroll.scrollTo(0, 0);
          }else{
            this.TikTokScroll.refresh();
          }
            let loadMore = document.getElementById("loadMore");
            this.TikTokScroll.on("scroll", pos => {
              let offsetHeight = this.$refs.TikTokWrapper&&this.$refs.TikTokWrapper.offsetHeight;
              if(offsetHeight){
                if (loadMore.offsetTop > offsetHeight && loadMore.offsetTop + pos.y < offsetHeight && this.isLoadMore) {
                  let page = this.page + 1;
                  this.getMoreData_TikTok(page);
                  setTimeout(() => {
                    this.TikTokScroll.refresh();
                  }, 800);
                }
              }
            })
        })
       ;
      })
    },
    getMoreData_TikTok(page){
      this.isLoadMore = false;
        $http.get('plugin.tiktok-cps.api.goods.good-list',{...this.tiktok_details,page},'').then(res=>{
          if(res.result == 0){
            return this.$toast(res.msg);
          }
          this.isLoadMore = true;
          this.tiktok_list = this.tiktok_list.concat(res.data.products);
          this.page = Number(res.data.current_page);
          this.total_page = Number(res.data.last_page);
        })

    },
    clickActive(data,index) {
      console.log(data,"data===")
      this.loading = true;
      //点击顶部滑动的分类事件
      // this.foodScroll.scrollTo(0, 0);
      if(this.decorate_config.classify_position==2){
       this.child_category_active = index;
      }
      // this.contentlist_one = {};
      if(this.decorate_config.classify_style==1){
        this.secondaryId = data.id;
        this.threeId  = data.id;
        this.foodInfo = [];
        this.ADImg = data.adv_img;
        this.ADUrl = data.adv_url;
        let level = data.name == '全部' ? 2 :3;
        this.get_classify_category(data.id,level,index);
      }else{
          this.chooseSecondary(data);
      }

    },
    get_recommend_list(page=1){
      $http.get('goods.classify.recommend-list',{page},'').then(({result,msg,data})=>{
        if(!result){
          this.$toast(msg)
        }
        this.page = data.current_page;
        this.total_page = data.last_page;
        this.secondaryId =(data.current_page==1&& data.data.length!==0)?data.data&&data.data[0].id:'';
        if(this.decorate_config.classify_style==1){

          if(data.current_page==1){
            this.titleInfo = data.data;
            this.list.recommend =  data.data;
          }else{
            this.titleInfo.concat(data.data);
            this.list.recommend.concat(data.data);
          }
          this.switch_flag = false;
          this.activatId = data.data[0].id;
          this.getData(data.data[0].id);
        }else{
          this.contentlist_one = {
            goo:true,
            data:data.current_page==1?data.data:this.contentlist_one.data.concat(data.data),
            set:{...this.list.set,cat_level:2},
          };
        }
        this.isLoadMore = true;
      })
    },
    allList() {
      this.switch_flag = false;
      this.activeName = [];
      this.ADImg = this.list.set.cat_adv_img_url;
      this.ADUrl = this.list.set.cat_adv_url;
      this.foodInfo = [];
      this.list.recommend = [];
      this.parentTitle = '';
      this.active2 = true;
      this.active = 9999;
      this.one_id = "";
      this.contentlist_one = {};
      this.get_recommend_list();
      if(this.decorate_config.inner_click == 3){
        this.parentTitle = '推荐分类';
        this.parentId = "";
      }
    },
    tabsa(n, i) {
      console.log(n,'n',i,'i');
      this.switch_flag = true;
      this.isLoadMore = false;
      this.loading = true;
      this.foodInfo = [];
      this.one_id = i.id;
      this.list.recommend = [];
      this.showTitle = "";
      if(this.decorate_config.classify_position==2){
        this.child_category_active = this.decorate_config.classify_style==1 ?1:0;
      }

      this.$store.commit("setAdvimg", i);
      //this.$store.state.category.adv_img
      this.active = n;
      this.active2 = false;
      this.lastIndex = n;
      if(this.current_goods_key == 'tiktok'){
        if(this.TikTokScroll){
          this.TikTokScroll.scrollTo(0, 0);
        }
        this.page=1;
        this.tiktok_details.cate_id = i.cate_id;
        this.getTikTokGoods();
      }else{
        this.contentlist_one = {};
        if(this.decorate_config.classify_style==1){
          this.ADImg = i.adv_img;
          this.ADUrl = i.adv_url;
          let level = i.parent_id == 0 ? 2 :3;
          this.secondaryId = i.id;
          this.threeId  = i.id;
          this.get_classify_category(i.id,level,n,'tabas');
        }else{
          if(this.list.set.cat_level==2 || this.decorate_config.inner_click == 3){
            this.ADImg = i.adv_img;
            this.ADUrl = i.adv_url;
            if(this.decorate_config.inner_click == 3){ //模板三
              this.parentTitle = i.name + '分类';
              this.parentId = '';
            }
          }else{
            this.parentTitle = i.name;
            this.parentId = i.id;
            this.ADImg = '';
            this.ADUrl = '';
          }

          this.getContentlist(i.id);

        }
      }

    },
    get_classify_category(parent_id,level,index,type='first'){
      this.threeInfo = [];
      this.activeName = [];
      $http.get("goods.classify.category",{parent_id},'').then(res=>{
        this.switch_flag = false;
        this.isCategoryPage = res.data.current_page;
        this.isCategory_total_page = res.data.last_page;
        if(res.result!==1){
          return this.$toast(res.msg);
        }
        let data = res.data.data,set=this.list.set;
        if(data&&data.length!==0){
          this.activatId = parent_id;
          if(level==2){
            this.isCategoryMore = res.data.last_page>res.data.current_page ? true : false;
            this.titleInfo = [{name:"全部",id:parent_id},...data];
            if(type=='tabas'){
              this.threeId = data[0].id;
            }
            this.$set(this.list,"recommend",[{name:"全部",id:parent_id},...data]);
            if(set.cat_level==3&&this.decorate_config.classify_position==2){
              this.get_classify_category(data[0].id,3,index,type);
            }else{
              let id =data[0].id;
              if(this.decorate_config.classify_position==1){
                id = parent_id;
              }
              this.getData(id);
            }
          }else{
            if((set.cat_level==3||level==3&&type!=='tabas')||this.decorate_config.classify_position==2){
                this.threeInfo = [{ name:"全部",id:parent_id},...data];
            }
            if(set.cat_level==3||level==3){
              this.getData(parent_id)
            }
          }
        }else{
          this.getData(parent_id)
          if(level==2){
            this.titleInfo = [{ name:"全部",id:parent_id}];
            this.list.recommend = [{ name:"全部",id:parent_id}];
            this.secondaryId =parent_id;
            if(set.cat_level == 3){
              this.threeInfo = [{ name:"全部",id:parent_id}];
            }
          }else{
              if(type!=='tabas'||this.decorate_config.classify_position==2){
                this.threeInfo.unshift({
                  name:"全部",id:parent_id
                });
              }
          }
          this.activatId = parent_id;
          this.threeId = parent_id;
          this.contentlist_one = {};
        }
        setTimeout(() => {
          this.activeName = [];
        }, 800);
        this.$nextTick(()=>{
          this._initScroll();
        })
      })

    },
    price_hidden(item = {}){
      if(this.decorate_config.classify_style == 1 && item.love_price_display_deduction && item.love_price_display_deduction.enable == 1){
        return 'price'
      }
      return 'price price_hidden'
    },
    info_c_height(item = {}){
      if(this.decorate_config.classify_style == 1  && item.love_price_display_deduction && item.love_price_display_deduction.enable == 1){
        return 'info_c info_c_height'
      }
      return 'info_c'
    },
    checkVipPrice(good={}){
      if(good.vip_level_status && good.vip_level_status.status == 1){
        return good.vip_level_status.word
      }else{
        return good.price_level == 1 ? good.vip_price : good.vip_next_price
      }
    },
    // 判断有没有区间价格
    checkPrice(item = {}) {
      if(item.vip_level_status && item.vip_level_status.status == 1){
        return item.vip_level_status.word;
      } else {
        if(this.decorate_config.classify_style==1 && item.love_price_display_deduction && item.love_price_display_deduction.enable == 1){
          let txt = `${item.love_price_display_deduction.goods_price}+${item.love_price_display_deduction.value}${item.love_price_display_deduction.name}`
          return txt
        }
        if(this.searchScreen.order_field == 'min_price' || this.searchScreen.order_field == 'max_price'){
          return item[this.searchScreen.order_field||'min_price'];// 如果有规格，区间价格同时受到排序选择（价格升降）的影响
        }else{
          return item['min_price'];
        }
      }
    },
    bpfun() {
      this.$router.push(this.fun.getUrl("brand"));
    },
    debounce() {
      // clearTimeout方法，以便控制连续触发带来的无用调用
      if (this.debounce_timer) {
        clearTimeout(this.debounce_timer); // 先清除之前的延时，并在下面重新开始计算时间
      }
      let that = this;
      this.debounce_timer = setTimeout(() => {
        // 800毫秒以后执行方法
        that.setScorll();
      }, 800); // 如果还没有执行就又被触发，会根据上面的clearTimeout来清除并重新开始计算
    },
    setScorll() {
      if (!this.$refs.goodsWrapper) {
        return;
      }
      if (!this.foodScroll) {
        this.foodScroll = new BScroll(this.$refs.goodsWrapper, {
          click: true,
          scrollY: true,
          probeType: 3,
          swipeBounceTime: 500,
          useTransition: false,
          mouseWheel: true
        });
      } else {
        this.foodScroll.refresh();
      }

      let loadMore = document.getElementById("loadMore");
      this.foodScroll.on("scroll", pos => {
        if (this.$refs.imgBox != undefined) {
          this.Height = this.$refs.imgBox.offsetHeight + 8;
        }
        this.scrollMargin = pos.y;
        if (loadMore.offsetTop > this.$refs.goodsWrapper.offsetHeight && loadMore.offsetTop + pos.y < this.$refs.goodsWrapper.offsetHeight && this.isLoadMore) {
          this.getMoreData_1(1);
          setTimeout(() => {
            this.foodScroll.refresh();
          }, 800);
        }
      });
    },
    //获取更多数据，加载更多
    getMoreData_1(_tag) {
      this.isLoadMore = false; // 防止多次请求分页数据
      this.isCategoryMore = false;
      const that = this;
      if (_tag == 1 && this.page >= this.total_page) {
        Toast("没有更多");
        return;
      } else if (_tag == 0 && this.isCategoryPage >= this.isCategory_total_page) {
        Toast("没有更多");
        return;
      } else {
        if(this.active2){
          let page = this.page + 1;
          return this.get_recommend_list(page);
        }
        _tag == 1 ? (that.page += 1) : (that.isCategoryPage += 1);
        // that.page += 1;
        $http
          .get(
            categoryApi.children,
            {
              parent_id: this.activatId,
              as_id: this.zoneId,
              page: _tag == 1 ? that.page : that.isCategoryPage
            },
            ""
          )
          .then(res => {
            this.loading = false;
            if (res.result == 1) {
              var nextPageData = res.data.data;
              if (_tag == 1) {
                that.isLoadMore = true;
                that.contentlist_one.data = that.contentlist_one.data.concat(nextPageData); //进行数组拼接
                return that.contentlist_one;
              } else {
                that.isCategoryMore = that.isCategoryPage >= that.isCategory_total_page ? false : true;
                let _recommend = that.list.recommend.concat(nextPageData); //进行数组拼接
                that.$delete(that.list, "recommend");
                that.$set(that.list, "recommend", _recommend);
              }
            } else {
              if (_tag == 1) {
                that.page = that.page - 1;
                that.isLoadMore = false;
              } else {
                that.isCategoryPage = that.isCategoryPage - 1;
                that.isCategoryMore = false;
              }
              return;
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    getContentlist(id) {
      this.one_id = id;
      this.activatId = id;
      let jsons = { parent_id: id, as_id: this.zoneId };
      $http.get(categoryApi.children, jsons, "").then(response => {
        this.loading = false;
        if (response.result == 1) {
          let data = response.data;
          this.isRecommend = false;
          this.err = false;
          this.contentlist_one.tjfl = false;
          this.contentlist_one.set =data.set;
          this.contentlist.top_img =data.top_img;
          this.isCategory_total_page = data.last_page;
          this.isCategoryMore = data.last_page > 1? true:false;
          this.isCategoryPage = 1;
          this.page = 1;
          this.total_page =data.last_page;
          this.LoadMoreTest =(this.page < this.total_page)? "加载更多":'没有更多';
          this.isLoadMore = true;

          if(this.decorate_config.classify_position==2){  //二级分类在左侧
            this.contentlist_one.goo = true;
            if(data.data.length!==0){
              let child_data =data.data[this.child_category_active];
              this.parentTitle = child_data.name||'';
              this.contentlist_one.set ={
                cat_adv_img:data.data[this.child_category_active].adv_img,
                cat_adv_url:data.data[this.child_category_active].adv_url,
                cat_level:data.set.cat_level
              };
              if(data.set.cat_level == '3'){
                this.contentlist_one.data = child_data.has_many_children||[];
              }else{
                this.contentlist_one.data = [];
              }
            }else{
              this.parentTitle="";
              this.contentlist_one.data=[];
              this.contentlist_one.set={};
            }
          }else{
            if(this.decorate_config.inner_click == 3){
              this.$set(this.contentlist_one,"set",{cat_level:2});
            }else{
              this.parentId = id;
              if(this.list.set.cat_level == 2){
                this.$set(this.contentlist_one,"goo",true);
              }else{
                this.$set(this.contentlist_one,"goo",false);
              }
            }
            this.$set(this.contentlist_one,"data",data.data);
          }
          let obj =  {
            set:this.list.set,
            recommend:data.data
          }
          console.log(this.contentlist_one,"contentlist_one=====")
          this.list = obj;
          if (this.foodScroll) {
            this.foodScroll.scrollTo(0, 0);
          }
          this.$nextTick(() => {
            this.debounce();
          });


          // this.total_page = data.goods_list&&data.goods_list.last_page||0;

          //------------------------------------------
        } else {
          this.err = true;
        }
      });
    },
    getMoreCategoryNew() {
      this.main_category_page++;
      if(this.current_goods_key == 'tiktok'){
        $http.get("plugin.tiktok-cps.api.goods.good-cate",{page:this.main_category_page}).then(res => {
          if(res.result == 0){
            return this.$toast(res.msg);
          }
          this.onelist = this.onelist.concat(res.data.data);
          this.main_category_total = res.data.last_page;
        })
        return;
      }
      let urlstr ="goods.classify.home";
      if(this.$route.name == 'coffee_machine_cate'){
        // urlstr = "plugin.coffee-machine.frontend.category.category-home";
        jsons["search[coffee_machine_id]"] = this.$route.params.machine_id;
        jsons.plugin = 'coffee'
      }
      $http.get(urlstr, { page: this.main_category_page }, "loading").then(response => {
        if (response.result === 1) {
          this.main_category_total = response.data.categoryList.last_page;
          this.onelist = this.onelist.concat(response.data.categoryList.data);
          this.$nextTick(() => {
            this.meunScroll.finishPullUp();
            this.meunScroll.refresh();
          });
        }
      });
    },
    getCategoryNew() {
      let jsons = { as_id: this.zoneId };
      // if (!this.fun.isTextEmpty) {
      //   jsons.parent_id = id;
      // }
      let urlstr = categoryApi.home;
      if(this.$route.name == 'coffee_machine_cate'){
        urlstr = "plugin.coffee-machine.frontend.category.category-home";
        jsons["search[coffee_machine_id]"] = this.$route.params.machine_id;
      }
      $http.get(urlstr, jsons, "loading").then(response => {
        if (response.result === 1) {
          let data = response.data;

          this.page = 1;
          this.isLoadMore = true;
          this.total_page = data.goods_list&&data.goods_list.last_page||0;
          this.LoadMoreTest = (this.page < this.total_page)? "加载更多":'没有更多';
          this.isRecommend = true;
          this.onelist = data.category.data;
          this.main_category_total = data.category.last_page;
          this.err = false;
          data.recommend.goo = true;
          this.cartInfo = data.member_cart;

          if(data.set&&data.set.cat_class == '0') this.foodInfo = data.goods_list.data;
          if (data.set.cat_brand && data.set.cat_brand.length > 0) {
            this.brandShow = data.set.cat_brand;
          }
          if (data.set.cat_class && data.set.cat_class.length > 0) {
            this.categoryShow = data.set.cat_class;
            this.ADImg = data.set.cat_adv_img;
            this.ADUrl = data.set.cat_adv_url;
            if (this.categoryShow == "1" && this.onelist.length > 0) {
              this.tabsa(0, this.onelist[0]);
            }
          }

          if (this.decorate_config.classify_style==1) {
            this.foodInfo = data.goods_list.data;
            this.contentlist.recommend = data.recommend;
            this.contentlist.set = data.set;
            this.contentlist.member_cart = data.member_cart;
            this.list = this.contentlist;
            this.setCatagory(this.contentlist);
          } else {
            this.contentlist_one.tjfl = true;
            this.contentlist_one.set = data.set;
            this.isLoadMore = false;
            if(data.set&&data.set.cat_class == "0"){
              this.contentlist_one.goo = true;
              this.contentlist_one.data = data.recommend;
              this.contentlist_one.set = {
                cat_adv_img:data.set.cat_adv_img,
                cat_adv_url:data.set.cat_adv_url,
                cat_level:2,
              }
              this.parentTitle = "";
            }else{
              this.contentlist_one.goo = false;
            }

            this.list = this.contentlist_one;
            if (this.foodScroll) {
              this.foodScroll.scrollTo(0, 0);
            }
            this.$nextTick(() => {
              // this.setScorll();
              this.debounce();
            });
          }
          this.$nextTick(() => {
            this._initScroll();
          });
          //------------------------------------------------
        } else {
          this.err = true;
        }
      });
    },

    //获取更多数据，加载更多
    getMoreData() {
      this.isLoadMore = false; // 防止多次请求分页数据
      const that = this;
      console.log(that.page,that.total_page,"页数==========")
      if (that.page >= that.total_page) {
        that.LoadMoreTest = "没有更多";
        return;
      } else {
        console.log("加载更多");
        that.page += 1;
        let price;
        if(this.searchScreen.top || this.searchScreen.mini){
          if(!this.searchScreen.mini){
            price = this.searchScreen.top
          }else{
            price = `${ this.searchScreen.mini }${ this.searchScreen.top ?','+this.searchScreen.top:this.searchScreen.top?this.searchScreen.top:'' }`
          }
        }
        let urlstr,json;
        json = {
          goods_page: that.page,
          category_id: that.activatId,
          order_field: this.searchScreen.order_field||'',
          order_by: this.searchScreen.order_by||'',
          "search[brand_id]": this.searchScreen.brandId||'',
          "search[product_attr]": this.searchScreen.attrstr||'',
          "search[filtering]": this.searchScreen.filterId||'',
          "search[price_range]":price || ""
        }
        console.log('dasdasdasd',that.$route.name)
        if(that.$route.name == 'coffee_machine_cate'){
          urlstr = "plugin.coffee-machine.frontend.category.get-goods-list-by-category-id";
          json["search[coffee_machine_id]"] = this.$route.params.machine_id
        }else{
          urlstr = categoryApi.goods
        }
        $http
          .get(
            urlstr,
            json,
            ""
          )
          .then(res => {
            that.isLoadMore = true;
            if (res.result == 1) {
              var nextPageData = res.data.data;
              that.foodInfo = that.foodInfo.concat(nextPageData); //进行数组拼接
              return that.foodInfo;
            } else {
              that.page = that.page - 1;
              that.isLoadMore = false;
              return;
            }
          })
          .catch(error => {
            console.log(error);
          });
      }
    },

    _initScroll() {
      if (!this.meunScroll) {
        this.meunScroll = new BScroll(this.$refs.menu, {
          click: true,
          pullUpLoad: true
        });
        this.meunScroll.on("pullingUp", () => {
          console.log("上拉加载更多",this.main_category_page , this.main_category_total);
          // 发送网络请求，请求更多页的数据
          if (this.main_category_page < this.main_category_total) {
            this.getMoreCategoryNew();
          }

          // 等数据请求完成，并且将新的数据展示出来后
          setTimeout(() => {
            this.meunScroll.finishPullUp();
          }, 2000);
        });
      } else {
        this.meunScroll.refresh();
      }
    },
    numberLeft(_id) {
      this.goodsCartsTotal[_id].total = Number(this.goodsCartsTotal[_id].total) - 1;
      if (this.goodsCartsTotal[_id].total <= 0) {
        //小于等于0 清空该商品购物车数量
        this.destroyData(this.goodsCarts[_id].id);
        return;
      } else {
        this.changeCount(this.goodsCarts[_id].id, this.goodsCartsTotal[_id].total);
      }
    },
    numberRight(_id, _stock, good) {
      if(good.plugin_id == '101'){
        // 预约商品点击进入商品详情
        this.gotoGoods(good.goods_id,good)
        return
      }
      //价格权限
      if (good.vip_level_status && good.vip_level_status.status == 1) {
        Toast(good.vip_level_status.tips);
        return false;
      }
        if (_stock == 0) {
          Toast("库存不足");
          return;
        }

      if (!this.fun.isTextEmpty(this.goodsCartsTotal[_id])) {
        if (this.goodsCartsTotal[_id].total >= _stock) {
          console.log("数量超出范围");
          Toast("库存不足");
          return;
        }
      }
      $http.get("member.member-cart.store", { goods_id: _id, total: 1 }, "").then(
        response => {
          if (response.result === 1) {
            if (!this.fun.isTextEmpty(this.goodsCartsTotal[_id])) {
              this.goodsCartsTotal[_id].total = Number(this.goodsCartsTotal[_id].total) + 1;
            }
            this.$store.commit("setCartNum", response.data.cart_num);
            this.updateData();
          } else {
            Toast(response.msg);
          }
        },
        response => {
          console.log(response);
        }
      );
    },
    clickCount(data) {
      OldGoodsNum = data;
    },
    changeCount(_id, _num, index, _good) {
      let that = this;
      if (_num <= 0) {
        this.destroyData(_id);
        return;
      }
      if (this.fun.isTextEmpty(_good) && _num - 1 >= optionsMaxCount) {
        //有规格的
        Toast("库存不足");
        return;
      } else if (!this.fun.isTextEmpty(_good) && _num >= _good.stock) {
        //无规格
        // console.log(that.goodsCartsTotal)
        // that.goodsCartsTotal[_good.id].total =5;
        this.$set(that.goodsCartsTotal[_good.id], "total", OldGoodsNum);
        Toast(`该商品最多购买数量为${_good.stock}`);
        return;
      }

      let json = {
        id: _id,
        num: _num
      };

      $http.get("member.member-cart.updateNumV2", json, "").then(
        response => {
          if (response.result === 1) {
            that.updateData();
            if (!that.fun.isTextEmpty(index)) {
              //规格商品
              switch (index) {
              case -1:
                that.popNum = that.popNum - 1;
                break;
              case 1:
                that.popNum = that.popNum + 1;
                break;
              default:
                console.log("error");
              }
            }
          } else {
            Toast(response.msg);
          }
        },
        response => {
          console.log(response);
        }
      );
    },
    updateData() {
      //更新购物车数据
      $http.get("member.member-cart.index", {}).then(response => {
        if (response.result === 1) {
          this.cartInfo = response.data; //更新购物车数据，避免不同步
          this.contentlist.member_cart = response.data;
          this.getCart(response.data);
        } else {
          Toast(response.msg);
        }
      });
    },
    destroyData(_cid) {
      //清除该购物车商品id
      let that = this;
      $http.get("member.member-cart.destroy", { ids: _cid }).then(response => {
        if (response.result == 1) {
          that.popNum = 0;
          let _num = this.$store.state.cart_num - 1;//注意这里是购物车数量，不是购物车商品数量哦
          this.$store.commit("setCartNum", _num);
          that.updateData();
        } else {
          Toast(response.msg);
        }
      });
    },
    change() {
      //关闭分类折叠面板
      this.activeName = [];
    },
    chooseSecondary(sInfo) {
      this.one_id=sInfo.parent_id;
      if (!this.isRecommend) {
        this.ADImg = sInfo.adv_img;
        this.ADUrl = sInfo.adv_url;
      }
      this.secondaryId = sInfo.id;
      this.parentTitle = sInfo.name;
      if (!this.fun.isTextEmpty(sInfo.has_many_children)) {
        this.activatId = sInfo.id;

        if(this.decorate_config.classify_style==1){
          this.threeInfo = [];
          this.threeId = sInfo.id;
          if(this.decorate_config.classify_position==1){
            this.SecondaryName = sInfo.name;
          }
          this.threeInfo = [{name:"全部",id:sInfo.id},...sInfo.has_many_children];
          this.getData(sInfo.id);
        }else{
          if(this.decorate_config.classify_position==2){
            // this.contentlist_one.goo = false;
            this.contentlist_one.set = {cat_adv_img:sInfo.adv_img,cat_adv_url:sInfo.adv_url};
            this.contentlist_one.data =sInfo.has_many_children;
          }
        }
        // this.chooseThree(sInfo.has_many_children[0].id);

      } else {
        this.threeId = null;
        this.threeInfo = [];
        this.activatId = sInfo.id;
        this.contentlist_one = {};
        if(this.decorate_config.classify_position==2){
          this.contentlist_one.set = {cat_adv_img:sInfo.adv_img,cat_adv_url:sInfo.adv_url};
          this.contentlist_one.goo = true;
        }
        this.getData(sInfo.id);
      }
    },
    chooseThree(_tid) {
      this.threeId = _tid;
      this.activatId = _tid;
      this.getData(_tid);
    },
    getData(_id) {
      let price;
      if(this.searchScreen.top || this.searchScreen.mini){
        if(!this.searchScreen.mini){
          price = this.searchScreen.top
        }else{
          price = `${ this.searchScreen.mini }${ this.searchScreen.top ?','+this.searchScreen.top:this.searchScreen.top?this.searchScreen.top:'' }`
        }
      }
      let jsons = {
        category_id: _id,
        goods_page: 1,
        order_field: this.searchScreen.order_field||'',
        order_by: this.searchScreen.order_by||'',
        "search[brand_id]": this.searchScreen.brandId||'',
        "search[product_attr]": this.searchScreen.attrstr||'',
        "search[filtering]": this.searchScreen.filterId||'',
        "search[price_range]":price || ""
      };
      let urlstr = categoryApi.goods;
      if(this.$route.name == 'coffee_machine_cate'){
        urlstr = "plugin.coffee-machine.frontend.category.get-goods-list-by-category-id";
        jsons["search[coffee_machine_id]"] = this.$route.params.machine_id;
      }
      $http.get(urlstr, jsons, "").then(response => {
        if (response.result == 1) {
          this.page = 1;
          this.loading = false;
          this.total_page = response.data&&response.data.last_page||0;
          this.LoadMoreTest = (this.page < this.total_page)?"加载更多":"没有更多";
          this.foodInfo = response.data.data;
          this.isLoadMore = true;
          if(this.foodScroll){
            // 因为设置0，0没效果所以设置0，1
            this.foodScroll.scrollTo(0, 1);
          }
          this.goodsWrapperBScroll("toTop");
          setTimeout(() => {
            this.activeName = [];
          }, 800);


        } else {
          console.log(response.msg);
        }
      });
    },
    /**
     * 如果传了商品，通过商品id获取购物车数量
     * @param goods
     */
    getCart(goods) {
      this.carts = goods;
      this.goodsCarts = [];
      this.cartIDs = [];
      this.carts.forEach(item => {
        this.$set(this.goodsCarts, item.goods_id, item);
        if (goods && goods.id === item.goods_id) {
          goods.buyNum = item.total;
        }
        if (item.goods_id === this.goodsInfo.id && item.option_id === optionsId) {
          this.popNum = item.total;
          this.popCard = item;
        }
        this.cartsNum += item.total;
        this.cartsTotal += item.total * item.goods.price;

        this.cartIDs.push(item.id);
      });
      this.goodsCartsTotal = this.calculateTotal(this.carts);
      this.goodsWrapperBScroll();
    },
    goodsWrapperBScroll(flag) {
      this.$nextTick(() => {
        if (!this.foodScroll) {
          this.foodScroll = new BScroll(this.$refs.goodsWrapper, {
            click: true,
            scrollY: true,
            probeType: 3,
            swipeBounceTime: 500,
            useTransition: false,
            mouseWheel: true
          });
        } else {
          this.foodScroll.refresh();
          if (flag === "toTop") {
            // 更新购物车的时候不用滚动到顶部
            setTimeout(() => {
              this.foodScroll.scrollTo(0, 0);
            }, 250);
          }
        }

        let loadMore = document.getElementById("loadMore");

        this.foodScroll.on("scroll", pos => {
          if (this.$refs.imgBox != undefined) {
            this.Height = this.$refs.imgBox.offsetHeight + 8;
          }
          this.scrollMargin = pos.y;
          if(loadMore.offsetTop!==0){
            if (this.$refs.goodsWrapper && loadMore.offsetTop + pos.y < this.$refs.goodsWrapper.offsetHeight && this.isLoadMore) {
              this.getMoreData();
              setTimeout(() => {
                this.foodScroll.refresh();
              }, 800);
            }

          }

        });
      });
    },
    //不同规格的同一商品求和
    calculateTotal(arr) {
      let newArr = [];
      let temp = {};
      let newArr2 = [];
      for (let i in arr) {
        let key = arr[i].goods_id;
        if (temp[key]) {
          let good_id = temp[key].goods_id;
          temp[key].goods_id = good_id;
          temp[key].total = temp[key].total + arr[i].total;
        } else {
          temp[key] = {};
          temp[key].goods_id = arr[i].goods_id;
          temp[key].total = arr[i].total;
        }
      }
      for (let k in temp) {
        newArr.push(temp[k]);
      }
      newArr.forEach(item => {
        this.$set(newArr2, item.goods_id, item);
      });
      return newArr2;
    },
    setCatagory(newVal) {
      //处理点击一级分类时，右侧的二级、三级子分类数据处理
      if (!this.fun.isTextEmpty(newVal.recommend)) {
        let add_allCategory = newVal.recommend;
        if (!this.active2&&this.decorate_config.classify_style==1&&this.decorate_config.classify_position==1) {
          add_allCategory.unshift({
            name: "全部",
            id: this.activatId,
            parent_id: this.activatId,
            adv_img: this.$store.state.category.adv_img,
            adv_url: this.$store.state.category.adv_url
          });
        }
        this.titleInfo = add_allCategory;
        this.secondaryId = newVal.recommend[0].id;
        if (newVal.set.cat_level == "3" && !this.fun.isTextEmpty(newVal.recommend[0].has_many_children)) {
          this.threeInfo = [];
          this.threeId = null;
          let _arr = newVal.recommend[0].has_many_children;
          _arr.unshift({name:"全部",id:newVal.recommend[0].id,})
          this.threeInfo = _arr;
          this.threeId = newVal.recommend[0].id;
          this.activatId = this.threeId;

          this.ADImg = newVal.recommend[0].adv_img;
          this.ADUrl = newVal.recommend[0].adv_url;
        } else {
          this.threeInfo = [];
          this.threeId = null;
          this.activatId = this.secondaryId;
        }
        this.activeName = [];
        if (this.foodScroll) {
          this.foodScroll.scrollTo(0, 0);
        }
        // this.getCart(newVal.member_cart);
      } else {
        this.titleInfo = [];
        this.showTitle = [];
        this.secondaryId = [];
        this.threeInfo = [];
        this.threeId = null;
        this.goodsWrapperBScroll("toTop");
      }
    },
    //添加有规格商品到购物车
    addGood(good) {
      if(good.plugin_id == '101'){
        // 预约商品点击进入商品详情
        this.gotoGoods(good.goods_id,good)
        return
      }
      //价格权限
      if (good.vip_level_status && good.vip_level_status.status == 1) {
        Toast(good.vip_level_status.tips);
        return false;
      }
      if(this.decorate_config.cart_style == 2 && good.has_option != 1 && good.plugin_id != 40){
        $http.get("member.member-cart.store", { goods_id: good.id, total: 1 }, "").then(
          response => {
            Toast(response.msg);
            if (response.result === 1) {
              if (!this.fun.isTextEmpty(this.goodsCartsTotal[ good.id])) {
                this.goodsCartsTotal[ good.id].total = Number(this.goodsCartsTotal[ good.id].total) + 1;
              }
              this.$store.commit("setCartNum", response.data.cart_num);
              this.updateData();
            }
          },
          response => {
            console.log(response);
          }
        );
        return;
      }

      this.show2 = true;
      this.goodsInfo = good;

      this.initPopView(); //初始化弹窗view
    },
    //初始化弹窗view
    initPopView() {
      optionsId = "";
      specsManage = [];
      this.specid = "";
      this.popNum = 0;
      if (this.goodsInfo.has_option === 1) {
        //是否有规格
        this.isShowMultiSpecsMemPrice(); //是否需要显示多规格会员价
        this.popTitle = this.goodsInfo.title; //设置默认图片
        this.popThumb = this.goodsInfo.thumb; //设置商品名
        this.popStock = this.goodsInfo.stock; //设置默认库存
        this.popCard = {};
        if (!this.specid.length) {
          if (this.goodsInfo.point_goods) {
            this.popPrice = this.goodsInfo.point_goods.min_point + "-" + this.goodsInfo.point_goods.max_point; //设置默认价格
          } else {
            this.popPrice = this.goodsInfo.min_price + "-" + this.goodsInfo.max_price; //设置默认价格
          }
        }

        this.goodsDescription = "请选择";
        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          this.goodsDescription += " " + this.goodsInfo.has_many_specs[i].title;
        }

        if (!optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
            if (this.goodsInfo.goods_option_ids && this.goodsInfo.goods_option_ids.length >= 0) {
              for (let j = 0; j < this.goodsInfo.has_many_specs[i].has_many_specs_item.length; j++) {
                if (this.goodsInfo.has_many_specs[i].has_many_specs_item[j].id == Number(this.goodsInfo.goods_option_ids[i])) {
                  this.selectSpecs(this.goodsInfo.has_many_specs[i].has_many_specs_item[j], this.goodsInfo.has_many_specs[i].has_many_specs_item[j].id);
                }
              }
            } else {
              this.selectSpecs(this.goodsInfo.has_many_specs[i].has_many_specs_item[0], this.goodsInfo.has_many_specs[i].has_many_specs_item[0].id);
            }
          }
        }
      } else {
        this.goodsDescription = "";
        optionsMaxCount = this.goodsInfo.stock; //设置最大购买量
      }
    },
    isShowMultiSpecsMemPrice() {
      //判断是否需要显示多规格会员价【#70785】
      if (this.goodsInfo.is_open_micro && Number(this.goodsInfo.is_open_micro) == 1 && this.goodsInfo.has_option == 1) {
        this.isMultiSpecs = true;
      } else {
        this.isMultiSpecs = false;
      }
    },

    //界面选择规格触发事件
    selectSpecs(data, id) {
      //处理选择池
      this.manageSpecs(data);

      //处理规格组合选择状态
      this.setGoodsSpecs(data);

      //设置选择规格后的 价格、照片、库存
      this.setGoodsSpecsChangeInfo(id);

      //判断当前购买总量与库存的关系
      this.getMaxCount();
    },

    //判断当前购买总量与库存的关系
    getMaxCount() {
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        if (optionsMaxCount == 0) {
          //库存不足
          this.popNum = 0;
        }
        if (this.popNum > optionsMaxCount) {
          this.popNum = optionsMaxCount;
        }
      }
    },

    //设置选择规格后的 价格、照片、库存
    setGoodsSpecsChangeInfo(id) {
      //根据ID 排序 specsManage.sort();
      specsManage.sort(function(a, b) {
        return a.id - b.id;
      });
      if (specsManage.length === this.goodsInfo.has_many_specs.length) {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"
        this.specid = goodsSpecs;
        for (let i = 0; i < this.goodsInfo.has_many_options.length; i++) {
          if (goodsSpecs === this.setGoodsSpecsBySort(this.goodsInfo.has_many_options[i].specs)) {
            this.popmPrice = this.goodsInfo.has_many_options[i].market_price; //设置价格
            if (this.goodsInfo.point_goods) {
              this.popPrice = this.goodsInfo.point_goods.point_option[i].goods_point; //设置价格
            } else {
              this.popPrice = this.goodsInfo.has_many_options[i].product_price; //设置价格
            }
            this.popThumb = this.fun.isTextEmpty(this.goodsInfo.has_many_options[i].thumb) ? this.goodsInfo.thumb : this.goodsInfo.has_many_options[i].thumb; //设置图片
            this.popStock = this.goodsInfo.has_many_options[i].stock; //设置库存

            optionsId = this.goodsInfo.has_many_options[i].id; //设置规格ID，用于生成订单
            optionsMaxCount = this.goodsInfo.has_many_options[i].stock; //库存最大数 用于切换更改买家购买数量
            // console.log("库存最大数",optionsMaxCount)
            if (optionsMaxCount > 0) {
              this.popNum = 0;
            }
            if (this.isMultiSpecs) this.getMemberPrice(optionsId);
            break;
          }
        }

        for (let i = 0; i < this.carts.length; i++) {
          if (this.carts[i].goods_id === this.goodsInfo.id && this.carts[i].option_id === optionsId) {
            this.popNum = this.carts[i].total;
            this.popCard = this.carts[i];
            break;
          }
          this.popNum = 0;
          this.popCard = {};
        }
      } else {
        let goodsSpecs = "";
        for (let j = 0; j < specsManage.length; j++) {
          goodsSpecs += specsManage[j].id + "_";
        }
        this.specid = goodsSpecs;
      }
    },

    //处理商品goodsSpecs 并排序 新方法
    setGoodsSpecsBySort(specs) {
      let _specs = specs.split("_"); //先变成数组
      //_specs.sort();//排序
      _specs.sort(function(a, b) {
        return a - b;
      });

      // 在组装回去
      let goodsSpecs = "";
      for (let j = 0; j < _specs.length; j++) {
        goodsSpecs += _specs[j] + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); //处理"_"

      return goodsSpecs;
    },

    //处理选择池
    manageSpecs(data) {
      var specsObject = new Object();
      specsObject.id = data.id;
      specsObject.specid = data.specid;
      specsObject.title = data.title;
      if (specsManage.length > 0) {
        for (let i = 0; i < specsManage.length; i++) {
          if (specsManage[i].specid == specsObject.specid) {
            specsManage.splice(i, 1);
          }
        }
        specsManage.push(specsObject);
      } else {
        specsManage.push(specsObject);
      }

      //排序
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        var newSpecsManage = [];
        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
              newSpecsManage.push(specsManage[j]);
              break;
            }
          }
        }
        specsManage = newSpecsManage;
      }
      this.setGoodsDescription();
    },

    //处理goodsDescription 数据
    setGoodsDescription() {
      var description = "";
      //相等代表全选了 体现语句
      if (specsManage.length == this.goodsInfo.has_many_specs.length) {
        description = "已选择 ";
        for (let i = 0; i < specsManage.length; i++) {
          description += specsManage[i].title + " ";
        }
        this.goodsDescription = description;
      } else {
        description = "请选择 ";

        for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
          for (let j = 0; j < specsManage.length; j++) {
            if (this.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
              description += this.goodsInfo.has_many_specs[i].title + " ";
              break;
            }
          }
        }
        this.goodsDescription = description;
      }
    },

    //处理规格组合选择状态 过滤数据
    setGoodsSpecs(specs) {
      for (let i = 0; i < this.goodsInfo.has_many_specs.length; i++) {
        if (specs.specid != this.goodsInfo.has_many_specs[i].id) {
          this.setGoodsSpecsStatus(this.goodsInfo.has_many_specs[i].has_many_specs_item, specs.id);
        }
      }
    },

    //处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
    setGoodsSpecsStatus(specitem, id) {
      let options = []; //数据池

      for (let i = 0; i < this.goodsInfo.has_many_options.length; i++) {
        let _specs = this.goodsInfo.has_many_options[i].specs.split("_");
        //判断是否包含
        for (let j = 0; j < _specs.length; j++) {
          if (_specs[j] == id) {
            options.push(this.goodsInfo.has_many_options[i]);
          }
        }
      }

      for (let m = 0; m < options.length; m++) {
        let _specs = options[m].specs.split("_");
        for (let y = 0; y < _specs.length; y++) {
          if (_specs[y] != id && options[m].stock == 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = true;
              }
            }
          } else if (_specs[y] != id && options[m].stock > 0) {
            for (let n = 0; n < specitem.length; n++) {
              if (_specs[y] == specitem[n].id) {
                specitem[n].c = false;
              }
            }
          }
        }
      }
    },
    //弹窗提交确认
    submitAction() {
      let that = this;
      console.log("弹窗提交确认", optionsMaxCount);
      if (specsManage.length < this.goodsInfo.has_many_specs.length) {
        //请选择规格
        // this.show2 = false;
        Toast(this.goodsDescription);
        return;
      }
      if (optionsMaxCount == 0) {
        Toast("该规格库存不足！");
        return;
      }
      $http.get("member.member-cart.store", { goods_id: this.goodsInfo.id, total: 1, option_id: optionsId }, "").then(
        response => {
          if (response.result === 1) {
            this.$store.commit("setCartNum", response.data.cart_num);
            Toast(response.msg);
            that.updateData();
            that.popNum = that.popNum + 1;
          } else {
            Toast(response.msg);
          }
        },
        response => {
          console.log(response);
        }
      );
    },
    close() {
      this.show2 = false;
    },
    gotosearch() {
      if(this.$route.name == 'coffee_machine_cate'){
        this.$router.push(
          this.fun.getUrl("coffee_machine_search", {
            machine_id: this.$route.params.machine_id,
          })
        );
        return
      }
      if (this.isSelfPickCategory) {
        //跳转供应商模板（关联自提点的）
        this.$router.push(this.fun.getUrl("selfPickSearch", { fromHome: 1 }));
        return;
      }
      if(this.current_goods_key == 'tiktok'){
        this.$router.push(this.fun.getUrl('TikTokSearch'));
        return;
      }
      this.$router.push(this.fun.getUrl("search", { fromHome: 1 }));
    },
    gotoGoods(gid, good) {
      if (good.category_option_id) {
        this.$router.push(this.fun.getUrl("goods", { id: gid, coid: good.category_option_id }));
      } else {
        this.$router.push(this.fun.getUrl("goods", { id: gid }));
      }
    },
    bindOneCategory(item) {
      if(this.active2&&this.decorate_config.inner_click == 3){
        let _result = this.onelist.filter(one_item=>one_item.id  == item.id);
        if(_result&&_result.length!==0){
          let index = 0;
          this.onelist.forEach((val, key) => {
            if (val.id == item.id) {
              index = key;
            }
          });
          this.tabsa(index, item);
          return;
        }
      }
      if(this.decorate_config.inner_click == 3){ //模板三
        if(this.list.set.cat_level == 3){
          this.$router.push(this.fun.getUrl("category_child", { id: item.id, fromHome:1 }));
        }else{
          this.$router.push(this.fun.getUrl('search', {id: item.id, fromHome:1 }));
        }
      }else{
        this.$router.push(this.fun.getUrl('search', {id: item.id, fromHome:1 }));
      }

    },
    async getNowPackageDeliver() {
      let deliverIDStorage = sessionStorage.getItem("deliverId") || null; //获取当前会话是否存储了自提点id
      let _href = window.location.href; //当前链接
      let lat, lng;
      if (deliverIDStorage) {
        //sessionStorage 有值，说明某个页面之前有请求记录过，可直接请求分类
        if (deliverIDStorage != this.deliverId) {
          this.deliverId = deliverIDStorage;
          // this.getCategoryNew();
          this.get_classify();
        }
        return;
      } else if (_href.indexOf("deliverId") > -1) {
        let _dID = this.fun.getKey("deliverId"); //获取链接上的参数，自提点id
        this.deliverId = _dID;
      } else {
        await this.fun
          .getLocation("正在定位中，请稍等")
          .then(res => {
            lat = res.point.lat;
            lng = res.point.lng;
          })
          .catch(err => {
            console.log("定位error：：", err);
          });
      }
      let _json = {};
      if (lat) {
        _json = {
          lng: lng || "",
          lat: lat || ""
        };
      }
      if (this.deliverId) {
        _json.deliver_id = this.deliverId;
      }

      $http.get("plugin.package-deliver.frontend.decorate-deliver.getNowPackageDeliver", _json, ".").then(
        response => {
          if (response.result === 1) {
            // this.getCategoryNew();
            this.get_classify();
            this.deliverId = response.data.id;
            window.sessionStorage.setItem("deliverId", response.data.id); //储存到sessionStorage
            this.fun.wxShare();
          } else {
            this.$toast(response.msg);
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    getMemberPrice(_optionsId) {
      if (!_optionsId) return;
      this.specsVIPPrc = 0;
      $http
        .post("goods.other-info.option-vpi-price", { option_id: _optionsId }, null, true)
        .then(res => {
          if (res.result == 1) {
            this.specsVIPPrc = res.data.vip_price || null;
          } else {
            this.specsVIPPrc = null;
          }
        })
        .catch(error => {
          this.specsVIPPrc = null;
          console.log(error);
        });
    },
    //通用功能
    showbox() {
      // 改变筛选框
      this.showGoodScreen = !this.showGoodScreen;
    },
    sortOut(e) {
      this.showGoodScreen = false;
      // if (this.goods.length == 0) {
      //   return;
      // }
      this.searchScreen.order_field = e.order_field;
      this.searchScreen.order_by = e.order_by;
      this.getData(this.activatId);
    },
    cloneGoodScreen(e){
      this.searchScreen = e;
      this.getData(this.activatId);
    },
    choose(index) {
      this.choose_index = index;
      let order_type = 0;
      if (index !== 1) {
        if (this.sort.up == 0 && this.sort.down == 0) {
          this.sort.up = 1;
        } else if (this.sort.up == 1) {
          this.sort.down = 1;
          this.sort.up = 0;
        } else if (this.sort.down == 1) {
          this.sort.up = 1;
          this.sort.down = 0;
        }
      } else if (this.choose_index == 1) {
        this.sort.up = 0;
        this.sort.down = 0;
      }
      if (this.sort.down == 1) {
        order_type = 1;
      }
      let search_type = index - 1;
      this.tiktok_details.search_type = search_type;
      this.tiktok_details.order_type = order_type;
      this.page = 1;
      this.tiktok_list=[];
      this.getTikTokGoods();
    },

    getwebdesImg(){
      $http.get("plugin.web-design.frontend.carousel.index","","").then(({result,msg,data})=>{
        if(result!==1){
          return this.$toast(msg);
        }
        this.webdesImage = data;
      })
    },
    get_classify(type=''){
      let urlstr = "goods.classify.home",
      jsons = {};
      if(this.$route.name == 'coffee_machine_cate'){
        // urlstr = "plugin.coffee-machine.frontend.category.category-home";
        jsons["search[coffee_machine_id]"] = this.$route.params.machine_id;
        jsons.plugin = 'coffee';
      }
      if(this.$route.name == "selfPickCategory"){
        jsons.plugin = 'supplier';
      }
      $http.get(urlstr,jsons,"").then( async ({result,data})=>{
        this.loading = false;
        if(result!==1){
          this.err = true;
          return this.$toast(res.msg);
        }

        this.isLoadMore = true;
        let  shop_set  = data.shop_set,
        decorate_config   = data.decorate_config,
        // decorate_config   = {
        //   classify_position:1,//二级分类显示位置：1=右侧；2=和一级分类显示左侧
        //   classify_style:2,//分类样式：1=左侧分类名称+右侧商品列表；2=左侧分类名称+右侧二级分类列表
        //   goods_sort:1,//商品排列方式：0=不显示；1=竖排两列；2=横排
        //   inner_click:3,//点击跳转：1=商品详情；2=搜索页；3=旧三级分类页
        //   cart_style:2,//购物车：0=不显示；1=加入购物车
        // },
        member_cart = data.member_cart,
        tab_list = data.decorate_config.tab,
        recommendList   = data.recommendList,
        categoryList   = data.categoryList;
        this.decorate_config = decorate_config;
        this.onelist = categoryList.data;
        this.isRecommend = true;
        this.page = recommendList.current_page;
        this.cartInfo  = member_cart;
        this.contentlist.member_cart  = member_cart;
        this.total_page = recommendList.last_page;
        this.list.set = {...shop_set};
        this.main_category_total = data.categoryList.last_page;
        this.err = false;
        this.isLoadMore = true;
        this.LoadMoreTest = (recommendList.current_page < recommendList.last_page)?'加载更多':'没有更多';
        if(type!=='tab'){
          if(tab_list&&tab_list.length!==0){
            this.commodity = true;
            tab_list.sort((a,b)=>{
              return a.sort - b.sort;
            })

            let _arr = tab_list.filter(item=>item.is_show);
            if(_arr.length!==0){
              if(_arr.length==1&&_arr[0].key == 'shop'){
                this.commodity = false;
              }
              this.current_goods_key = _arr[0].key;
              this.tab_list = _arr;
              if(_arr[0].key=='tiktok'){
                this.onChangeGoods(_arr[0]);
                return;
              }
            }
          }
        }
        if(shop_set){
          this.brandShow = shop_set.cat_brand;
          this.categoryShow = shop_set.cat_class;
          if(shop_set.web_design_enable && Number(shop_set.web_design_enable)){
            this.getwebdesImg();
          }
          if(shop_set.cat_class=='1'&&categoryList.data.length>0){
            this.tabsa(0, categoryList.data[0]);
            return;
          }else{
            this.ADImg = shop_set.cat_adv_img;
            this.ADUrl = shop_set.cat_adv_url;
            this.foodInfo = [];
          }
        
        }
        if(decorate_config.classify_style==1){//分类样式-左侧分类名称+右侧商品列表
          this.list.recommend=recommendList.data;
          this.titleInfo = recommendList.data;
          if(decorate_config.inner_click == 3){
            this.contentlist.recommend = recommendList.data;
            this.contentlist.set = {...shop_set,cat_level:2};
          }else{
            this.contentlist.recommend = recommendList.data;
            this.contentlist.set = shop_set;
          }
          let secondaryId = "",activatId="";
          if(shop_set&&shop_set.cat_class=="0"){
            secondaryId = recommendList?.data[0]?.id||'';
            activatId =  recommendList?.data[0]?.id||'';
          }else{
            secondaryId = categoryList.data[0].id;
            activatId = categoryList.data[0].id;
          }
          this.secondaryId = secondaryId;
          this.activatId = activatId;
          if(shop_set.cat_class!=="1"){
            // this.activeName = [];
            this.getData(secondaryId)
          }
          this.$nextTick(()=>{
            this.updateData();
          })
          // this.setCatagory(this.contentlist);
        }else{//分类样式-左侧分类名称+右侧二级分类列表
          this.contentlist_one.data = recommendList.data;
          this.contentlist_one.tjfl = true;
          this.contentlist_one.set = shop_set;
          if(shop_set.cat_class=="0"){
            this.contentlist_one.goo = true;
            this.contentlist_one.data = recommendList.data;
            this.contentlist_one.set = {
              cat_adv_img:data.shop_set.cat_adv_img,
              cat_adv_url:data.shop_set.cat_adv_url,
              cat_level:2,
            }
            if(decorate_config.inner_click=='3'){
              this.parentTitle = "推荐分类";
            }else{
              this.parentTitle = "";
            }
          }else{
            this.contentlist_one.goo = false;
          }

          if(this.decorate_config.classify_position==2){
            this.list.recommend=recommendList.data;
          }
          this.isLoadMore = false;
          if (this.foodScroll) {
            this.foodScroll.scrollTo(0, 0);
          }
          this.$nextTick(() => {
            this.debounce();
          });
        }
        this.$nextTick(() => {
          this._initScroll();
          this.init_head_height();
        });
      })
    },
  },
   mounted() {
    //区分是否首页跳转进来
    this.isset = localStorage.getItem("isset");
    localStorage.removeItem("isset");
    this.isGetCart = false;

  },
  created() {
    if (this.$route.name == "selfPickCategory") {
      this.isSelfPickCategory = false;
    }else{
      this.get_classify();
    }
  },
  activated() {
    this.isSelfPickCategory = this.$route.name == "selfPickCategory" ? true : false;
    if (this.$route.name == "selfPickCategory") {//自提点关联供应商
       //获取自提点信息
       categoryApi = {
        home: "plugin.supplier.frontend.category.category-home",
        children: "plugin.supplier.frontend.category.get-children-category",
        goods: "plugin.supplier.frontend.category.get-goods-list-by-category-id"
      };
      this.getNowPackageDeliver();
    }

    if (this.isGetCart && this.decorate_config.classify_style == 1) {
      this.$nextTick(() => {
        this.updateData();
      });
    } else {
      this.isGetCart = true;
    }
    this.fun.setWXTitle($i18n.t("分类"));

    // if(this.brandShow=='' && this.categoryShow==''){
    //     this.active = 0;
    // }
    if(this.foodScroll) this.foodScroll.refresh();//解决在滑动过程中切换页面后，返回该分类页出现商品列表滑动不了
  },
  watch: {
    activeName: function(newVal) {
      if(this.active2){
        this.first_category_name = '推荐分类';
      }else{
        this.first_category_name = this.onelist[this.active].name;
      }
      if (newVal == "1") {
        this.showTitle = [];
      } else {
        if(this.switch_flag){
          this.showTitle = [];
        }else{
          this.showTitle = this.titleInfo;
        }
        //分类排序，使得当前分类排在最前
      }
    },
    scrollMargin(newVal) {
      if (this.$refs.imgBox != undefined) {
        if (newVal < -this.Height) {
          this.$refs.imgBox.style.marginTop = `-${this.Height}px`;
        } else {

            this.$refs.imgBox.style.marginTop = `${newVal}px`;
        }
      }
    }
  },
  components: { cCarcontent, cCarcontent4, cSort , goodScreen,VanImage,Skeleton}
};
